#!/bin/bash

clear

RED="\e[31m"
GREEN="\e[32m"
YELLOW="\e[33m"
BLUE="\e[34m"
RESET="\e[0m"

PATCHES=(
    "icu-75.1-2-aarch64.pkg.tar.xz https://gitee.com/haanxuan/arch/raw/main/ARM/icu-75.1-2-aarch64.pkg.tar.xz tar -xf"
    "libxml2-2.13.5-2-aarch64.pkg.tar.xz https://gitee.com/haanxuan/arch/raw/main/ARM/libxml2-2.13.5-2-aarch64.pkg.tar.xz tar -xf"
)

function error_exit {
    echo -e "${RED}$1${RESET}"
    exit 1
}

function success_msg {
    echo -e "${GREEN}$1${RESET}"
}

function warn_msg {
    echo -e "${YELLOW}$1${RESET}"
}

function info_msg {
    echo -e "${BLUE}$1${RESET}"
}

function check_arch {
    [[ "$(uname -m)" != "aarch64" ]] && error_exit "仅支持 aarch64\n$(uname -m)"
}

function check_pacman_lock {
    if [[ -f /var/lib/pacman/db.lck ]]; then
        warn_msg "发现 pacman 锁文件，尝试移除..."
        rm -rfv /var/lib/pacman/db.lck || error_exit "无法删除 pacman 锁文件，请手动处理！"
        success_msg "已移除 pacman 锁文件"
    fi
}

function check_or_install_chromium {
    if ! command -v chromium; then
        warn_msg "未检测到 Chromium，开始安装..."
        check_pacman_lock
        pacman -Sy --noconfirm chromium || error_exit "Chromium 安装失败"
        success_msg "Chromium 安装成功"
    fi

    if ! chromium --version; then
        echo -e "${BLUE}少女祈祷中...${RESET}"
    else
        success_msg "Chromium 运行正常，无需补丁"
        exit 0
    fi
}

function apply_patches {
    for patch in "${PATCHES[@]}"; do
        IFS=' ' read -r filename url extract_cmd <<<"$patch"
        info_msg "📥 下载 $filename"
        curl -LO "$url" || error_exit "下载 $filename 失败"

        info_msg "📦 解压 $filename"
        eval "$extract_cmd $filename -C /" || error_exit "解压 $filename 失败"

        rm -f "$filename"
    done
    ln -sf /usr/lib/libFLAC.so.14 /usr/lib/libFLAC.so.12
    success_msg "✅"
    chromium --version
}

check_arch
check_or_install_chromium
apply_patches
